package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.R;
import com.example.domain.User;
import com.example.service.UserService;
import com.example.utils.ValidateCodeUtils;
import io.netty.util.internal.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 登录
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map,HttpSession session){
        if (StringUtil.isNullOrEmpty(map.get("code").toString())){
            return R.error("请输入验证码");
        }
        //String correctCode = (String) session.getAttribute(map.get("phone").toString());
        //从Redis中获取验证码
        String correctCode = (String) redisTemplate.opsForValue().get(map.get("phone").toString());
        if (correctCode!=null&&correctCode.equals(map.get("code").toString())){
            User one = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getPhone, map.get("phone").toString()));
            if (one==null){
                one = new User();
                one.setPhone(map.get("phone").toString());
                userService.save(one);
            }
            session.setAttribute("user",one.getId());

            //如果用户登录成功，删除Redis中的验证码
            redisTemplate.delete(map.get("phone").toString());
            return R.success(one);
        }else {
            return R.error("验证码均为1234，需要在5分钟内输入验证码，否则请重新点击获取验证码");
        }

    }

    /**
     * 根据手机获取验证码（发送短信或者用固定验证码的方式不发短信），并暂时存储
     * 放入
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsgApi(@RequestBody User user, HttpSession session){
        String phone = user.getPhone();

        //手机号非空
        if (StringUtils.isNotEmpty(phone)){
            //随机生成4位验证码
            //String code = ValidateCodeUtils.generateValidateCode(4).toString();
            String code="1234";//由于没有用短信功能

            //调用阿里云的短信服务API（要付费还没申请）
            //...

            //存入session（后期优化可以放入缓存）
            //session.setAttribute(phone,code);

            //优化放入Redis中并设置超时时间5分钟
            redisTemplate.opsForValue().set(phone,"1234",5, TimeUnit.MINUTES);
            return R.success("验证码发送成功");
        }

        return R.error("验证码发送失败");
    }

    @PostMapping("/loginout")
    public R<String> loginout(HttpServletRequest request){
        //清除用户登录的session
        request.getSession().removeAttribute("user");
        return R.success("退出成功");
    }
}
